package com.lhy.admin.common.mvcplus.wrapper.mybatis;

import com.baomidou.mybatisplus.core.conditions.SharedString;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.lhy.admin.util.ReflectionUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * MyUpdateWrapper 提供LambdaUpdateWrapper 转 UpdateWrapper
 *
 * @author hyluan
 * @date 2022年07月29日 15:08
 */
public class MyUpdateWrapper<T> extends UpdateWrapper<T> {
    public MyUpdateWrapper(T entity, List<String> sqlSet, AtomicInteger paramNameSeq, Map<String, Object> paramNameValuePairs, MergeSegments mergeSegments, SharedString paramAlias, SharedString lastSql, SharedString sqlComment, SharedString sqlFirst) {
        super.setEntity(entity);
        if (sqlSet != null) {
            ReflectionUtils.setFieldValue(this, "sqlSet", sqlSet);
        }
        this.paramNameSeq = paramNameSeq == null ? new AtomicInteger(0) : paramNameSeq;
        this.paramNameValuePairs = paramNameValuePairs;
        this.expression = mergeSegments;
        this.paramAlias = paramAlias;
        this.lastSql = lastSql;
        this.sqlComment = sqlComment;
        this.sqlFirst = sqlFirst;
    }

    public MyUpdateWrapper(LambdaUpdateWrapper<T> updateWrapper) {
        this(updateWrapper.getEntity(),
                Arrays.stream(updateWrapper.getSqlSet().split(",")).collect(Collectors.toList()),
                (AtomicInteger) ReflectionUtils.getFieldValue(updateWrapper, "paramNameSeq"),
                updateWrapper.getParamNameValuePairs(),
                updateWrapper.getExpression(),
                new SharedString(updateWrapper.getParamAlias()),
                (SharedString) ReflectionUtils.getFieldValue(updateWrapper, "lastSql"),
                (SharedString) ReflectionUtils.getFieldValue(updateWrapper, "sqlComment"),
                (SharedString) ReflectionUtils.getFieldValue(updateWrapper, "sqlFirst"));
    }

}
